package cn.elwy.rcp.ui.table.listener;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IConfigurationElement;
import org.eclipse.core.runtime.Platform;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.elwy.common.util.AssertUtil;
import cn.elwy.common.util.ConvertTypeUtil;
import cn.elwy.common.util.sort.SortUtil;
import cn.elwy.rcp.ui.table.TablePlugin;

public class OpenListenerFactory {

  private static Logger logger = LoggerFactory.getLogger(OpenListenerFactory.class);

  private static Map<String, List<OpenListener>> openListenerMap = new HashMap<String, List<OpenListener>>();
  // private static OpenListenerFactory openListenerFactory = new OpenListenerFactory();
  static {
    init();
  }

  private OpenListenerFactory() {
    init();
  }

  public static List<OpenListener> getOpenListener(String id) {
    return openListenerMap.get(id);
  }

  public static void init() {
    IConfigurationElement[] openProviders = Platform.getExtensionRegistry()
        .getConfigurationElementsFor(TablePlugin.PLUGIN_ID, "openProvider");
    for (IConfigurationElement openProvider : openProviders) {

      String columnId = openProvider.getAttribute("id");

      List<OpenListener> openListenerList = new ArrayList<OpenListener>();
      System.out.println(openListenerList);
      IConfigurationElement[] openListenerElements = openProvider.getChildren("openListener");
      for (IConfigurationElement openListenerElement : openListenerElements) {
        String contentProviderAttribute = openListenerElement.getAttribute("class");
        if (AssertUtil.isNotEmpty(contentProviderAttribute)) {
          OpenListener op = createInstence(openListenerElement, "class");
          String id = openListenerElement.getAttribute("id");
          String name1 = openListenerElement.getAttribute("name");
          int index = ConvertTypeUtil.toInteger(openListenerElement.getAttribute("index"), 1);

          op.setId(id);
          op.setName(name1);
          op.setIndex(index);
          openListenerList.add(op);
        }
      }
      SortUtil.sort(openListenerList, true, "index");
      openListenerMap.put(columnId, openListenerList);
    }
  }

  @SuppressWarnings("unchecked")
  private static <T> T createInstence(IConfigurationElement element, String propertyName) {
    try {
      return (T) element.createExecutableExtension(propertyName);
    } catch (CoreException e) {
      logger.error(e.getMessage(), e);
    }
    return null;
  }

}
